package com.wugh.fast.module.web.conf;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.wugh.fast.kernel.core.props.FastProperties;
import com.wugh.fast.kernel.core.props.WebProperties;
import com.wugh.fast.module.web.ControllerLoggerAspect;
import com.wugh.fast.module.web.GlobalExceptionHandler;
import com.wugh.fast.module.web.RequestParameterConverter;
import com.wugh.fast.module.web.deserializer.DateDeserializer;
import com.wugh.fast.module.web.deserializer.StringDeserializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.web.bind.annotation.ControllerAdvice;

import java.util.Date;

/**
 * 说明:
 *
 * @author wugh
 * @date 2019-01-30 16:54
 */
@Configuration
public class FastWebAutoConfiguration {
    @Autowired
    private FastProperties fastProperties;

    @Bean
    @ConditionalOnProperty(prefix = WebProperties.PROPERTY_PREFIX, name = "controller-log", havingValue = "true", matchIfMissing = true)
    public ControllerLoggerAspect getControllerLoggerAspect() {
        return new ControllerLoggerAspect();
    }

    @Bean
    @ConditionalOnProperty(prefix = WebProperties.PROPERTY_PREFIX, name = "global-exception-handler", havingValue = "true", matchIfMissing = true)
    public GlobalExceptionHandler getGlobalExceptionHandler() {
        return new GlobalExceptionHandler();
    }

    /**
     * springmvc 的参数处理
     * <pre>
     *     string: 自动去除空白
     *     date: 多个格式自动转换
     * </pre>
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(RequestParameterConverter.class)
    public RequestParameterConverter getRequestParameterConverter() {
        RequestParameterConverter requestParameterConverter = new RequestParameterConverter();
        requestParameterConverter.setTrim(fastProperties.getWeb().getTrim());
        return requestParameterConverter;
    }

    /**
     * springmvc的json反序列化自动处理
     * <pre>
     *     string: 自动去除空白
     *     date: 多个格式自动转换
     * </pre>
     *
     * @param builder
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper getObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.build();
        SimpleModule simpleModule = new SimpleModule();
        if (fastProperties.getWeb().getTrim()) {
            simpleModule.addDeserializer(String.class, new StringDeserializer());
        }
        simpleModule.addDeserializer(Date.class, new DateDeserializer());
        objectMapper.registerModule(simpleModule);
        return objectMapper;
    }


}
